package demo.md5auth;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

import java.util.Arrays;

/**
 * Created by stephen on 2021-04-04 23:23 .
 * Description:
 */
public class CustomMd5RealmTest {

    public static void main(String[] args) {
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        // 注入自定义realm
        CustomMd5Realm realm = new CustomMd5Realm();
        // 使用hash
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        // 设置hash算法名称为md5
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        // 散列次数
        hashedCredentialsMatcher.setHashIterations(1024);
        realm.setCredentialsMatcher(hashedCredentialsMatcher);
        securityManager.setRealm(realm);
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "123");

        try {
            subject.login(token);
            System.out.println("登录成功");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        }

        if (subject.isAuthenticated()) { // 认证通过
            // 基于角色
            System.out.println("角色判断======================================");
            System.out.println(subject.hasRole("user")); // 有某一个角色
            System.out.println(subject.hasAllRoles(Arrays.asList("admin","user","abc"))); // 同时拥有
            boolean[] booleans = subject.hasRoles(Arrays.asList("admin", "abc")); // 分别判断
            for (boolean b : booleans) {
                System.out.println(b);
            }

            // 基于权限字符串,语法 资源标识符:操作:资源类型
            System.out.println("权限字符串判断===============================");
            System.out.println(subject.isPermitted("user:*:01"));

        }


    }
}
